

#include "../include/rdma_transporter.h"


struct message {
	
	uint32_t msg_size;
	char *buf;
};


char *gen_random_string(size_t len){
	int flag;
	char *str;
	srand((unsigned) time(NULL));
	str = (char *) malloc(len + 1);
	for(int i = 0; i < len; i++){
		flag = rand() % 3;
		switch(flag){
			case 0:
				str[i] = 'A' + rand() % 26;
				break;
			case 1:
				str[i] = 'a' + rand() % 26;
				break;
			case 2:
				str[i] = '0' + rand() % 10;
				break;
			default:
				str[i] = 'x';
				break;
		}
	}
	str[len] = '1';
	return str;

}




void init(rdma_fd *handler){
    char *server = "tstore01";
    uint16_t port = 9001;
    int sock = client_exchange(server, port);
    handler->fd = sock;
    context_info *ib_info = (context_info *)malloc(sizeof(context_info));
    open_device_and_alloc_pd(ib_info);
    get_context_info(handler, ib_info);
    build_rdma_connection(handler);
}
void init2(rdma_fd *handler){
    char *server = "tstore02";
    uint16_t port = 9001;
    int sock = client_exchange(server, port);
    handler->fd = sock;
    context_info *ib_info = (context_info *)malloc(sizeof(context_info));
    open_device_and_alloc_pd(ib_info);
    get_context_info(handler, ib_info);
    build_rdma_connection(handler);

}

int main(){

    rdma_fd *handler = (rdma_fd *)malloc(sizeof(rdma_fd));
    rdma_fd *handler2 =(rdma_fd *)malloc(sizeof(rdma_fd));
    init(handler);
    init2(handler2);
    message *msg = (message *) malloc(sizeof(message));
    srand((unsigned) time(NULL));
    //msg->msg_size = rand() % 1024;
    char *first_section = (char *)malloc(sizeof(char) * 5);
    for(int i = 0; i < 2; i++ ){
		msg->msg_size = rand() % 1024;
		memcpy(first_section, (char *)&msg->msg_size, sizeof(uint32_t));
    	*(first_section + 4)  = '1';
    	rdma_write(handler, first_section, 5);
    	rdma_write(handler2, first_section, 5);
    	msg->buf = gen_random_string(msg->msg_size);
    	rdma_write(handler, msg->buf,  msg->msg_size + 1);
    	rdma_write(handler2, msg->buf, msg->msg_size + 1);
        for(int i = 0; i < msg->msg_size;i++){
            printf("%02x ", msg->buf[i]);
        }
        printf("\n");
		free(msg->buf);
    }
    free(msg);
    while(1);
    return 0;

}
